//获取右方画室信息模块
define('studioInfo', ['config', 'cookie', 'jquery', 'handlebars'], function(config, cookie, $, Handlebars){
	//定义hanlebars helper
	function helper(){
		//判断头像是否为空
		Handlebars.registerHelper('if_empty', function(value, options){
			if(value == ''){
				return options.fn(this);
			}
			else{
				return options.inverse(this);
			}
		});
		//判断用户是否关注
		Handlebars.registerHelper('if_watched', function(value, options){
			if(value == 1){
				return options.fn(this);
			}
			else{
				return options.inverse(this);
			}
		});
	}


	//返回函数列表
	return {
		//获取画室详情
		getStudioById: function(studioId){
			var userId = cookie.getCookie('userId');
			var problem_request = $.ajax({
				url: config['api']['getStudioInfo'][0].replace('<studio_id>', studioId),
				type: config['api']['getStudioInfo'][1],
				data: {
					userId: userId
				},
				dataType: 'json',
				async: true,
				error: function(err){
					console.log('get studioInfo failed!');
				},
				success: function(data){
					console.log(data);
					//注册helper
					helper();
					//模板生成画室信息
					var source = $("#studio-template").html();
					var template = Handlebars.compile(source);
					$('.studio-info').html(template(data['studio']));
				}
			});
		},
		clickWatch: function(){
			$(document).on('click', '.studio-container .follow', function(){
				var userId = cookie.getCookie('userId');
				if (userId != ''){
					var isWatched = $(this).attr('data-isWatched');
					var studioId = $(this).parents('.studio-container').attr('data-studioId');
					//取消关注
					if (isWatched == 1){
						var request = $.ajax({
							url: config['api']['deleteStudio'][0].replace('<user_id>', userId),
							type: config['api']['deleteStudio'][1],
							data: {
								studioId: studioId
							},
							dataType: 'json',
							async: true,
							err: function(err){
								console.log(err);
								alert('取消关注失败!');
							},
							success: function(data){
								$('.studio-container .follow').attr('src', 'image/follow.png')
								alert('已取消关注画室!');
							}
						});
					}	
					//关注
					else if (isWatched == 0){
						var request = $.ajax({
							url: config['api']['followStudio'][0].replace('<user_id>', userId),
							type: config['api']['followStudio'][1],
							data: {
								studioId: studioId
							},
							dataType: 'json',
							async: true,
							err: function(err){
								console.log(err);
								alert('关注失败!');
							},
							success: function(data){
								$('.studio-container .follow').attr('src','image/unfollow.png' );
								alert('成功关注画室!');
							}
						});
					}
				}
				else{
					//还原右上角登录图标
					$('#top_bar .user').css('display', 'none');
					$('#top_bar .log_reg').css('display', 'inline');
					//取消画室已关注
					$(this).attr({'data-isWatched': 0, 'src': 'image/follow.png'});
					alert('请先登录！');
				}
			});
		}
	};
});
